import { Init, Provide } from '@midwayjs/core';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { GoodsPromoMjEntity } from '../entity/promo_mj';

/**
 * 促销满减服务
 */
@Provide()
export class GoodsPromoMjService extends BaseService {
  @InjectEntityModel(GoodsPromoMjEntity)
  promoMjEntity: Repository<GoodsPromoMjEntity>;

  @Init()
  async init() {
    await super.init();
    this.setEntity(this.promoMjEntity);
  }

  /**
   * 根据单据号获取满减明细
   * @param billNo 单据号
   */
  async getByBillNo(billNo: string) {
    return await this.promoMjEntity.find({
      where: { billNo, status: 1 },
      order: { billSn: 'ASC' }
    });
  }

  /**
   * 获取所有满减促销明细
   */
  async getAllActiveDetails() {
    return await this.promoMjEntity.find({
      where: { status: 1 },
      order: { createTime: 'DESC' }
    });
  }

  /**
   * 计算满减优惠
   * @param billNo 单据号
   * @param totalAmount 订单总金额
   */
  async calculateDiscount(billNo: string, totalAmount: number) {
    const details = await this.getByBillNo(billNo);
    
    // 找到符合条件的最大满减档位
    const applicableDetail = details
      .filter(detail => totalAmount >= detail.taxAmount)
      .sort((a, b) => b.taxAmount - a.taxAmount)[0];

    if (!applicableDetail) {
      return { discount: 0, message: '未达到满减条件' };
    }

    // 计算折扣金额：如果dedRate是98，表示打98折，优惠金额是原价的2%
    const discount = totalAmount - (totalAmount * applicableDetail.dedRate / 100);
    
    return {
      discount,
      originalAmount: totalAmount,
      finalAmount: totalAmount - discount,
      condition: applicableDetail.taxAmount,
      discountRate: applicableDetail.dedRate
    };
  }

  /**
   * 获取满减条件列表
   * @param billNo 单据号
   */
  async getDiscountConditions(billNo: string) {
    const details = await this.getByBillNo(billNo);
    return details.map(detail => ({
      condition: detail.taxAmount,
      discountRate: detail.dedRate,
      description: `满${detail.taxAmount}元打${detail.dedRate}折`
    }));
  }
} 